package com.etouch.security.security;

import com.etouch.security.pojo.dto.SysRoleDTO;
import com.etouch.security.pojo.dto.SysUserDTO;
import com.etouch.security.service.SysUserService;
import com.etouch.security.util.MobileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 自定义的认证用户获取服务类
 */
@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserService sysUserService;

    /**
     * 根据用户名获取认证用户信息
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (StringUtils.isEmpty(username)) {
            log.info("UserDetailsService没有接收到用户账号");
            throw new UsernameNotFoundException("UserDetailsService没有接收到用户账号");
        } else {
            //根据用户名查找用户信息
            SysUserDTO sysUserDTO = null;
            if (MobileUtil.isMobileNO(username)) {
                //手机号验证码登陆
                sysUserDTO = sysUserService.getUserByPhone(username);
            } else {
                //用户名, 密码登陆
                sysUserDTO = sysUserService.getUserByUserName(username);
            }
            if (sysUserDTO == null) {
                throw new UsernameNotFoundException(String.format("用户不存在", username));
            }
            //新建权限集合
            List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
            //模拟从数据库获取角色权限
            List<SysRoleDTO> sysRoleDTOList = sysUserDTO.getSysRoleDTOList();
            for (SysRoleDTO sysRoleDTO : sysRoleDTOList) {
                //封装用户信息和角色信息到SecurityContextHolder全局缓存中
                grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_" + sysRoleDTO.getRoleName()));
            }

            //创建一个用于认证的用户对象并返回，包括：用户名，密码，角色
            return new User(sysUserDTO.getUsername(), sysUserDTO.getPassword(), grantedAuthorities);
        }
    }
}
